<?php
namespace app\admin\controller;
use think\Db;
use think\Loader;

class Cate extends Base{
    //栏目列表
    public function lst(){
        $cateres = Db::name('cate') -> order('id ASC')-> select();
        $this -> assign('cateres', $cateres);
        return $this -> fetch();
    }

    //新增栏目
    public function add(){
        if(request() -> isPost()){
            $data = [
                'catename' => input('catename'),
                'keywords' => input('keywords'),
                'desc' => input('desc'),
                'type' => input('type') ? input('type') : 0,
            ];
            $validate = Loader::validate('Cate');
            if($validate-> check($data)){
                $db = Db::name('cate') -> insert($data);
                if($db){
                    return $this -> success('添加栏目成功！', 'lst');
                }else{
                    return $this -> error('添加栏目失败！');
                }
            }else{
                return $this -> error($validate -> getError());
            }
            return;
        }

        return $this -> fetch();
    }

    //修改栏目
    public function edit(){
        if(request() ->isPost()){
            $data = [
                'id' => input('id'),
                'catename' => input('catename'),
                'keywords' => input('keywords'),
                'desc' => input('desc'),
                'type' => input('type'),
            ];
            $validate = Loader::validate('Cate');
            if($validate ->scene('edit')  -> check($data)){
                $res = Db::name('cate')->update($data);
                if($res){
                    return $this -> success('修改栏目成功！', 'cate/lst');
                }else{
                    return $this -> error('修改栏目失败！');
                }
            }else{
                return $this -> error($validate -> getError());
            }
            return;

        }else{
            $id = input('id');
            $cates = db('cate') -> where('id', $id) -> find();
            $this -> assign('cates', $cates);
            return $this -> fetch();
        }

    }

    //删除栏目
    public function del(){
        $id = input('id');
        if(db('cate') -> delete($id)){
            return $this -> success('删除栏目成功！', 'cate/lst');
        }else{
            return $this -> error('删除栏目失败！');
        }
    }


}